<?php
/**
 * Created by PhpStorm.
 * User: Administratorjing
 * Date: 2018/3/27/027
 * Time: 20:38
 */

namespace app\api\service;


use app\lib\enum\ScopeEnum;
use app\lib\exception\TokenException;
use app\lib\exception\WeChatException;
use think\Exception;
use app\api\model\User as UserModel;

class UserToken extends Token
{
    protected $code;
    protected $wxAppID;
    protected $wxAppSecret;
    protected $wxLoginUrl;
    function __construct($code)
    {
        $this->code = $code;
        $this->wxAppID = config('wx.app_id');
        $this->wxAppSecret = config('wx.app_secret');
        $this->wxLoginUrl = sprintf(config('wx.login_url'),$this->wxAppID,$this->wxAppSecret,$this->code);
    }

    /**
     * get the code
     * @param $code
     * @throws Exception
     */
    public function get($code)
    {
        $result = curl_get($this->wxLoginUrl);
        $wxResult = json_encode($result,true);
        if(empty($wxResult)){
           throw new Exception('获取session_key及openID时异常，微信内部错误');
        }else{
            $loginFail = array_key_exists('errcode',$wxResult);
            if($loginFail){
                $this->processLoginError($wxResult);
            }else{
                $this->grantToken($wxResult);
            }
        }
    }

    private function grantToken($wxResult)
    {
        //逻辑
        //拿到openid
        //在数据库里面看是否存在openid,如果存在那么新增一条user记录
        //生成令牌，准备缓存数据，写入缓存
        //把令牌返回到客户端
        //take openid
        $openid = $wxResult['openid'];
        $user = UserModel::getByOpenID($openid);
        if($user){
            $uid = $user->id;
        }else{
            $uid = $this->newUser($openid);
        }
        $cachedValue = $this->prepareCachedValue($wxResult,$uid);
        $token = $this->saveToCache($cachedValue);
        return $token;
    }

    private function saveToCache($cachedValue)
    {
        //Generate token
        $key = self::generateToken();
        $value = json_encode($cachedValue);
        $expire_in = config('setting.token_expire_in');
        $request = cache($key,$value,$expire_in);
        if($request){
            throw new TokenException([
                'msg' => '服务缓存异常',
                'errorCode' => 10005
            ]);
        }
        return $key;
    }

    /**
     * prepare cache
     * @param $wxResult
     * @param $uid
     * @return mixed
     */
    private function prepareCachedValue($wxResult,$uid)
    {
        $cachedValue = $wxResult;
        $cachedValue['uid'] = $uid;
        //16 代表app用户的权限赋值
        //32 代表cms 管理员用户权限数值
        $cachedValue['scope'] = ScopeEnum::User;
        return $cachedValue;
    }

    /**
     * get the openid for UserModel
     * @param $openid
     * @return mixed
     */
    private function newUser($openid)
    {
        //创建
        $user = UserModel::create([
           'openid' => $openid
        ]);
        return $user->id;
    }

    /**
     * throw the errors message
     * @param $wxResult
     * @throws WeChatException
     */
    private function processLoginError($wxResult)
    {
        //直接抛出异常
        throw new WeChatException([
            'msg' => $wxResult['errmsg'],
            'errorCode' => $wxResult['errcode']
        ]);
    }
}